package com.mongodb.mongodb;

import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserRepository userRepository;

    @GetMapping("/get")
    public List<User> getUser() {
        return userRepository.findAll();
    }

    @GetMapping("getName")
    public List<User> getName(String name) {
        User user = new User();
        user.setName(name);
        ExampleMatcher matching = ExampleMatcher.matching().
                withIgnorePaths("id", "age", "createTime").
                withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<User> example = Example.of(user, matching);
        return userRepository.findAll(example);
    }

    @GetMapping("getById")
    public User getById(String id) {
        return userRepository.findById(id).get();
    }

    //http://localhost:8080/user/page?pageNumber=1&pageSize=10&name=
    @GetMapping(value = "/page")
    public Page<User> readUsersByPage(Integer pageNumber, Integer pageSize, String name) {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize, sort);
        User user = new User();
        user.setName(name);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //采用“包含匹配”的方式查询
                .withIgnorePaths("id", "age", "createTime");//忽略不查询字段
        Example<User> example = Example.of(user, matcher);
        return userRepository.findAll(example, pageRequest);
    }


    @RequestMapping("/add")
    public void insert() {
        User user = new User();
        user.setId(1);
        user.setName("战三");
        user.setAge(18);
        userRepository.insert(user);
    }


    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        userRepository.deleteById(id);
        return "delete success";
    }

    @PutMapping("/update")
    public void update(User user) {
        userRepository.save(user);
    }
}

